package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron = "0 * * * * ? ")//每分钟执行一次
    public void processTimeOutOrder() {
        log.info("处理超时订单");

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//看是否有超过15分钟的订单
        //看看是否还有超过15分钟的订单还在待支付
        List<Orders> orders = orderMapper.processTimeOutOrder(Orders.PENDING_PAYMENT, time);

        if (orders != null) {
            for (Orders order : orders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }

//    /**
//     * 处理待接单状态太久的订单
//     */
//    @Scheduled(cron = "0 * * * * ? ")//每分钟执行一次
//    public void processweijiedan() {
//        log.info("处理待接单状态太久的订单");
//
//        LocalDateTime time = LocalDateTime.now().plusMinutes(-10);//看是否有超过10分钟的订单
//        List<Orders> orders = orderMapper.processTimeOutOrder(Orders.TO_BE_CONFIRMED, time);
//
//        if (orders != null) {
//            for (Orders order : orders) {
//                order.setStatus(Orders.CANCELLED);
//                order.setCancelReason("接单超时，自动取消");
//                order.setCancelTime(LocalDateTime.now());
//                orderMapper.update(order);
//            }
//        }
//    }

    /**
     * 处理处于派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ? ")//每天凌晨1点执行
    public void processDeliveryOrder() {
        log.info("处理取消订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//看是否有超过60分钟的订单
        //看看是否还有超过60分钟的订单还在派送中
        List<Orders> orders = orderMapper.processTimeOutOrder(Orders.DELIVERY_IN_PROGRESS, time);

        if (orders != null) {
            for (Orders order : orders) {
                order.setStatus(Orders.COMPLETED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            }
        }
    }
}
